<?php
/**
 * Created by PhpStorm.
 * User: My
 * Date: 2018/11/27
 * Time: 12:28
 */

namespace App\Http\Helper;


class DataTransHelper
{
    /**
     * 转换答题为数组
     * @param $answerStr
     * @return array
     */
    public static function convertAnswer($answerStr) {
        $answers = [];
        $answerArr = explode('##', $answerStr);
        if(count($answerArr) > 0){
            foreach ($answerArr as $answer){
                $singleArr = explode(':', $answer);
                if(count($singleArr) > 0){
                    $obj['index'] = $singleArr[0];
                    $obj['weight'] = self::formatWeight($singleArr[1]);
                    $obj['answer'] = $singleArr[2];
                    array_push($answers, $obj);
                }
            }
        }
        return $answers;
    }

    /**
     * 将答案数组还原为字符串
     * @param $arrAnswers
     * @return string
     */
    public static function arrToStr($arrAnswers){
        $arr = [];
        $answers = [];
        foreach($arrAnswers as $k => $v){
            $arr[0] = $v['index'];
            $arr[1] = $v['weight'];
            $arr[2] = $v['answer'];
            $str=implode(":", $arr);
            $answers[$k]=$str;
        }
        $answerStr = implode("##", $answers);
        return $answerStr;
    }

    /**
     * 转换四项答题为数组
     * @param $answerStr
     * @return array
     */
    public static function convertFourAnswer($answerStr) {
        $answers = [];
        $answerArr = explode('##', $answerStr);

        if (count($answerArr) > 0) {
            foreach ($answerArr as $answer) {
                $singleArr = explode(':', $answer);
                if (count($singleArr) > 0) {
                    $obj['id'] = $singleArr[0];
                    $obj['value'] = $singleArr[1];
                    $obj['weight'] = $singleArr[2];
                    $obj['answer'] = $singleArr[3];

                    array_push($answers, $obj);
                }
            }
        }

        return $answers;
    }

    /**
     * 将四项答案数组还原为字符串
     * @param $arrAnswers
     * @return string
     */
    public static function arrFourToStr($arrAnswers){
        $arr = [];
        $answers = [];
        foreach($arrAnswers as $k => $v){
            $arr[0] = $v['id'];
            $arr[1] = $v['value'];
            $arr[2] = $v['weight'];
            $arr[3] = $v['answer'];

            $str=implode(":", $arr);
            $answers[$k]=$str;
        }
        $answerStr = implode("##", $answers);

        return $answerStr;
    }

    /**
     * 多选题格式化权重
     * @param string $str 提交权重字符串
     * @return number
     */
    public static function formatWeight($str){
        $arr = explode("|||", $str);
        return array_sum($arr);
    }
}